<template>
	<view class="paly">
		<view class="video-container" >		
			<video-player
				class="video-player"
				id="myVideo"
				ref="myVideoRef"
			    :albumId="openDramaId" 
			    :episodeId="openEpisodeId"
			    autoplay
				@play="playhandler"
				@ended="HandleplayEnd"
				version="1"
				:cloud-type="1"
				@timeupdate="Handbindtimeupdate"
				show-playback-rate-btn
				show-screen-lock-button 
			>
			</video-player>
			<!-- VIP视频蒙层 -->
			<view class="vip-mask" v-if="isVipMask" @click="handleVipMaskClick"></view>
		</view>
		<!-- <view class="notice" v-if="isNotice">
			<u-notice-bar mode="horizontal" :list="noticeList" close-icon @close="close"></u-notice-bar>
		</view> -->
		<view class="contrls">
			<view class="contrls-item">
				<view class="search" @click="handleZujian1">
					<image src="@/static/icon/last.png" ></image>
					<!-- <image src="@/static/icon/search-active.png" v-else></image> -->
					上次观看
				</view>
			</view>
			<view class="contrls-item">
				<view :class="isZujian2?'search-active':'search'" >
					<image src="@/static/icon/speed.png"  v-if="!isZujian2"></image>
					<!-- 倍速选择 -->
					<picker @change="bindSpeedChange" :value="SpeedIndex" :range="SpeedArray">
						<view  v-if="SpeedIndex === 1 ">倍速选择</view>
						<view v-else>{{SpeedArray[SpeedIndex]}}</view>
					</picker>
				</view>
			</view>
			<view class="contrls-item">
				<view :class="isZujian3?'search-active':'search'">
					<image src="@/static/icon/play-lines.png"  v-if="!isZujian3"></image>
					<!-- <view v-if="!isZujian3">线路选择</view> -->
					<!-- 线路选择 -->
					<picker @change="bindLineChange" :value="LineIndex" :range="LineArray">
						<view  v-if="LineIndex == 0 && !isZujian3 ">线路选择</view>
						<view v-else>{{LineArray[LineIndex]}}</view>
					</picker>
				</view>
			</view>
			<view class="contrls-item">
				<view :class="['auto-play-btn', isZujian4?'search-active':'search']" @click="handleZujian4">
					<image src="@/static/icon/auto-play.png" v-if="!isZujian4" class="auto-play-icon"></image>
					自动续播
				</view>
			</view>
		</view>
		<view class="content">
			<view class="header">
				<view class="header-left">
					<view class="title">{{details.name || ''}}</view>
				</view>
				<view class="header-right" @click="handleAddWatch">
					<image src="@/static/icon/favorite.png" v-if="!details.is_in_favorite" ></image>
					<image src="@/static/icon/favorited.png"v-else></image>
				</view>
			</view>

			<view class="tag-list">
				<view class="tag-item">
					<image src="@/static/icon/all-watch.png"></image>
					{{(details.drama_extension && details.drama_extension.all_watch) || 0}}
				</view>
				<view class="tag-item">
					<image src="@/static/icon/all-click.png"></image>
					{{(details.drama_extension && details.drama_extension.all_click) || 0}}
				</view>
				<view class="tag-item" v-for="(item,index) in keywordList" :key="index">
					{{item}}
				</view>
			</view>

			<view class="gather">
				<view class="gather-left">
					<view class="gather-title">选集列表</view>
					<view class="gather-text">观看至第{{EpisodeIndex}}集 · 全{{episodeTotal}}集
					</view>
				</view>
				<view class="gather-right">
					<view :class="isSearch?'search-active':'search'" @click="this.isSearch = !this.isSearch">
						<image src="@/static/icon/new-search.png" v-if="!isSearch"></image>
						<image src="@/static/icon/new-search-sctive.png" v-else></image>
						搜索
					</view>
				</view>
			</view>
			<view class="search-cotnent" v-if="isSearch">
				<input ref='searchInput' type="number" placeholder="请输入想要搜索的集数" @input="getInputValue"/> 
				<view class="right">
					<span @click="this.isSearch = !this.isSearch">取消</span>|
					<span @click="handleSearch" style="color:#aa55ff">搜索</span>
				</view>
			</view>
			<view class="gather-cotnent">
				<scroll-view scroll-x="true" class="scroll-x" :scroll-into-view="scrollToView"
					@scrolltolower="gatherLowerBottom" :lower-threshold="50">
					<!-- 分页按钮：每30个集数为一页 -->
					<view class="gather-team" v-for="(p, i) in chapterPageCount" :key="i">
						<view class="page-btn" :class="currentPageIndex===i? 'active' : ''" @click="switchPage(i)">
							{{ (i*30 + 1) }}-{{ Math.min((i+1)*30, episodeTotal) }}
						</view>
					</view>
				</scroll-view>
				<view class="gather-list">
					<view :id="'item-' + item.id"
						:class="['gather-item', (EpisodeIndex === (currentPageIndex*30 + index+1)) ? 'gather-active':'gather-noram']"
						v-for="(item,index) in currentPageepisodeList" :key="item.id" @click="setGatherNum(currentPageIndex*30 + index+1)">
						{{item.episode_index}}
						<view class="vip" v-if="item.is_vip">VIP</view>
					</view>
				</view>
				
			</view>


			<!-- 猜你喜欢 -->
			<view class="my-lovely">
				<Lovely :liveList="liveList"></Lovely>
			</view>
		</view>
		
		<view class="my-mask" v-if="isStopMask">该页面涉及隐私,禁止用户录屏</view>

	<!-- 集数：改为页面内展示，无弹窗 -->

		<!-- 充值 -->
		<PopupRecharge :isRecharge.sync="isRecharge" @recharge-success="onRechargeSuccess"></PopupRecharge>

	</view>
</template>

<script>

	import { nextTick } from "vue"
import Lovely from './components/lovely/index.vue'
	import PopupRecharge from './components/popup-recharge/index.vue'
	import {
		displayTips
	} from '@/common/Newapp.js'
	import {
		getDramaDetail,
		getEpisodeShow,
		getEpisodeCatalogue,
		getEpisodeAdd,
		getGuessYouLikes,
		getUserWatchRecordAdd,
		Login,
		getOriginId
	} from '@/request/api.js'
	export default {
		components: {
			Lovely,
			PopupRecharge
		},
		data() {
			return {
				codeList: [1051012001, 1051012002], // 错误码弹窗
				pageSize: 100,
				page: 1,
				noticeList: [
					'温馨提示:',
					'若支付成功后效益未生效',
					'请下拉刷新页面!!!'
				], //喇叭文字
				isNotice: true, //喇叭控制
				DramaId: 0, //内部剧目ID
				EpisodeId: 0, //内部剧集id
				EpisodeIndex: 1, //内部当前选中剧集序号
				episodeList: [], //剧集列表
				episodeMore: false, //滑动控制
				episodeLoader: false, //滑动控制
				episodeTotal: 0, //总集数
				episodeDetail: {}, //剧集详情
				details: {}, //剧集详情
				progress: 0, //播放进度
				currentTime:0,//播放秒数
				duration:0,//剧集总时长
				keywordList: [], //标签合集
				liveList: [], //猜你喜欢
				isRecharge: false, //充值弹窗
				scrollToView: '', //滚动id
				isStopMask:false,//录屏覆盖遮罩层
				isVipMask: false, // VIP视频蒙层控制
				vipTimer: null, // VIP计时器
				episodeListCount: 0, // 分页数（每30集为一页）
				currentPageIndex: 0,// 当前页索引（每页30集）
				pendingEpisode: null, // 存储被拦截的待播放剧集 { item, index }
				openDramaId:"",
				openEpisodeId:"",
				freeTime:6,
				isSearch:false ,//搜索剧集展示按钮
				inputValue:1,//搜索集数(默认)
				isZujian1:false,//展示视频组件1
				isZujian2:false,//展示视频组件2-倍速选择
				isZujian3:false,//展示视频组件3
				isZujian4: uni.getStorageSync('autoPlayNext') || false, //展示视频组件4-自动续播，从本地存储读取
				SpeedArray:['0.75倍速', '1倍速', '1.25倍速', '1.5倍速', '2倍速'], //倍速选择选项
				SpeedIndex:1,//默认倍速选择
				LineArray:['线路一','线路二','线路三'], //线路选择选项
				LineIndex:0,//默认线路选择
				preIndex:0//保留当前剧集数
		}
		},
		async onLoad(option) {
			//
			// 获取初始化剧目id和剧集序号，处理内部id和外部id
			this.DramaId = Number(option.drama_id)
			this.EpisodeIndex = Number(option.episode_index ? option.episode_index : 1)
			//抖音id存在时获取,(例如锚点进入),提前预加载
			if(option.tt_album_id && option.tt_episode_id){
				this.openDramaId =option.tt_album_id
				this.openEpisodeId=option.tt_episode_id
				this.preloadplaylet()
				const result = await getOriginId({
					open_drama_id:this.openDramaId
				})
				this.DramaId =result.data.drama_id
			}
			this.init()
		},
		// onPullDownRefresh() {
		// 	this.init()
		// },
		onReady(){
			//初始视频组件
			 this.videoContext = tt.createVideoContext('myVideo');
			console.log('this.videoContext', this.videoContext);
		},
		onUnload() {
			this.SaveHistory()
			// 清除计时器
			if (this.vipTimer) {
				clearInterval(this.vipTimer)
				this.vipTimer = null
			}
		},
		onShow() {
			tt.onUserScreenRecord((e) => {
				if (e.state == 'start') {
					this.isStopMask = true
				} else {
					this.isStopMask = false
				}
			})
		},
		onHide() {
			this.SaveHistory()
			// 清除计时器
			if (this.vipTimer) {
				clearInterval(this.vipTimer)
				this.vipTimer = null
			}
		},

		onShareAppMessage(res) {
			return {
				title: "观看精彩后续内容",
				path: `/pages/Detail/Detail?id=${this.DramaId}&episode_id=${this.EpisodeId}`,
			}
		},

		methods: {
			async init() {
				try {
					
					await this.handleDramaDetail() // 剧目详情
					await this.handleEpisodeDetail() // 剧集详情
					await this.getEpisodeList() // 剧集列表
					await this.getLiveList() // 猜你喜欢
				} catch (error) {
					console.error('初始化错误:', error)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				}
			},
			
			//播放组件
			async playhandler(){
				console.log('play')
				
			},
			// 剧目详情
			async handleDramaDetail() {
				const result = await getDramaDetail({
						drama_id:this.DramaId
				})
				this.details = result.data
				this.keywordList = result.data.tags.length > 0 ? result.data.tags.split(/[,，]/) : ''
				uni.setNavigationBarTitle({
					title: result.data.name,
				})
				
				//判断是否有指定剧集数，如果有就设置对应的剧集序号以及进度跳转，如果没有就用观看历史记录
				if (this.EpisodeId === 0) {
					//应用观看历史
					if (Object.keys(result.data.user_watch_history).length !== 0) {
						this.EpisodeIndex = result.data.user_watch_history.episode_index
						// this.progress = result.data.user_watch_history.watch_progress
						setTimeout(()=>{
							this.$u.toast('根据上次观看记录，已自动跳转')
						},1000)
					}
				}else{
					
				}
			},

			// 剧集详情(初始)
			async handleEpisodeDetail() {
				const result = await getEpisodeShow({
					drama_id: this.DramaId,
					episode_index: this.EpisodeIndex
				})
				this.episodeDetail = result.data
				// this.EpisodeIndex = result.data.episode_index
				//获取抖音剧目id和剧集id
				this.openDramaId = result.data.tiktok_drama.open_drama_id
				this.openEpisodeId = result.data.tiktok_drama.open_episode_id
				
				// 判断是否是会员集数
				if (result.data.is_vip && result.data.is_free_watch === false) {
					// 清除之前的计时器
					if (this.vipTimer) {
						clearInterval(this.vipTimer)
						this.vipTimer = null
					}
					// 开始计时器循环检查
					this.vipTimer = setInterval(() => {
						console.log(this.currentTime, '检查currentTime');
						//试看时长
						if (this.currentTime >= this.freeTime) {
							// 检测是否全屏，如果是则先退出全屏
							this.videoContext.exitFullScreen()
							// 延迟一下再暂停，确保退出全屏完成
							setTimeout(() => {
								this.videoContext.seek(this.freeTime)
								this.videoContext.pause()
								this.pendingEpisode = { index: this.EpisodeIndex }
								//暂停视频，显示VIP蒙层
								this.isVipMask = true
								this.$u.toast('试看已结束，请充值观看后续精彩剧情')
							}, 300)
							// 清除计时器
							clearInterval(this.vipTimer)
							this.vipTimer = null
						}
					}, 1000) // 每秒检查一次
					return
				} else {
					// 非VIP视频，隐藏蒙层并清除计时器
					this.isVipMask = false
					if (this.vipTimer) {
						clearInterval(this.vipTimer)
						this.vipTimer = null
					}
				}
				// 判断当前集数是否有观看进度,提醒用户并跳转
				// if (this.details.user_watch_history.episode_index === this.EpisodeIndex) {
				// 	this.progress = this.details.user_watch_history.watch_progress
				// 	console.log(1111);
				// 	this.videoContext.seek(10)
				// }
			},

			// 切换集数
			async setGatherNum(index) {
				//先保留当前集数，再切换
				this.preIndex = this.EpisodeIndex
				//切换剧集数先，清除蒙层和计时器
				this.isVipMask = false
				if (this.vipTimer) {
					clearInterval(this.vipTimer)
					this.vipTimer = null
				}
				this.EpisodeIndex = index
				// 计算并更新当前页索引（每页30集）
				this.currentPageIndex = Math.floor((index - 1) / 30)
				// 确保对应页的数据已加载
				const needCount = (this.currentPageIndex + 1) * 30
				if (this.episodeList.length < needCount && !this.episodeMore) {
					const nextPage = Math.ceil(this.episodeList.length / this.pageSize) + 1
					await this.getEpisodeList(nextPage)
				}
				await this.handleEpisodeDetail()
				// 滚动到对应的集数位置
				this.$nextTick(() => {
					const targetItem = this.currentPageepisodeList.find((item, idx) => {
						return (this.currentPageIndex * 30 + idx + 1) === index
					})
					if (targetItem) {
						this.scrollToView = 'item-' + targetItem.id
					}
				})
				// 如果该集需要会员（非免费），则暂停并显示VIP蒙层
				// if (item && (item.is_vip === true && item.is_free_watch === false)) {
				// 	if(this.currentTime >= 10){
				// 		this.videoContext.pause()
				// 		// 存储为 pendingEpisode，以便充值成功后自动播放
				// 		this.pendingEpisode = { item: item, index: index }
				// 		this.isVipMask = true
				// 	}
				// 	return
				// }else{
				// 	this.videoContext.seek(10)
				// }

			},
			
			// 点击VIP蒙层，弹出充值弹窗
			handleVipMaskClick() {
				this.isRecharge = true
			},

			// 加载剧集列表
			async getEpisodeList(page) {
				//首次加载为第一页
				if(!page){page =this.page}
				const result = await getEpisodeCatalogue({
					drama_id: this.DramaId,
					page:page,
					page_size: this.pageSize
				})
				const list = result.data.data
				this.episodeList = [...this.episodeList, ...list]
				this.episodeTotal = result.data.page_info.total
				//模拟剧集
				// this.episodeList = [...this.episodeList, ...list,...list,...list,...list,...list,...list]
				// this.episodeTotal = result.data.page_info.total*6
				if (this.episodeList.length >= result.data.page_info.total) {
					this.episodeMore = true
				}
			},

			// 剧集加载
			gatherLowerBottom() {
				if (this.episodeMore || this.episodeLoader) return
				this.page++
				this.getEpisodeList(this.page);
			},
			// 分页切换：每页30集
			switchPage(i) {
				this.currentPageIndex = i
				const needCount = (i + 1) * 30
				if (this.episodeList.length < needCount && !this.episodeMore) {
					const nextPage = Math.ceil(this.episodeList.length / this.pageSize) + 1
					this.getEpisodeList(nextPage)
				}
			},


			// 充值成功回调
			onRechargeSuccess(payload) {
				// 隐藏VIP蒙层
				this.isVipMask = false
				if (this.pendingEpisode) {
					const { item, index } = this.pendingEpisode
					this.pendingEpisode = null
					// 直接播放该集，设置 type 为 play
					this.setGatherNum(index, 'play')
				}
				// 可根据 payload 进行额外处理，如刷新会员状态
			},


			// 收藏
			async handleAddWatch() {
				if (this.details.is_in_favorite) {
					this.$u.toast('已存在我的收藏中')
					return
				}
				const resnut = await getEpisodeAdd({
					drama_id: this.DramaId
				})
				if (resnut.status_code === 200) {
					this.$u.toast('添加成功')
					this.details.is_in_favorite = true
				}
			},
			//实时记录保存阅读进度
			Handbindtimeupdate(e){
				this.currentTime = e.detail.currentTime
				this.duration = e.detail.duration
				this.progress = Math.floor((e.detail.currentTime/e.detail.duration)*100)
				// console.log(this.currentTime,this.duration,this.progress,'this.currentTime,this.duration,this.progress');
			},
			// 保存阅读记录
			SaveHistory() {
				getUserWatchRecordAdd({
					drama_id: this.DramaId,
					episode_index: this.EpisodeIndex,
					watch_progress: this.progress
				})
			},


			// 猜你喜欢
			async getLiveList() {
				const result = await getGuessYouLikes({
					drama_id: this.DramaId,
					category_id: 71
				})
				for (var index = 0; index < 11; index++) {
					this.liveList.push(result.data[0])
				}
				// this.liveList = result.data
			},
			//获取输入的值
			getInputValue(e){
				this.inputValue = e.detail.value
			},
			//处理搜索
			handleSearch(){
				//切换对应集数，并关闭搜索框
				const targetIndex = Number(this.inputValue)
				if(!targetIndex || targetIndex < 1 || targetIndex > this.episodeTotal){
					this.$u.toast('请输入正确的集数')
					return
				}
				
				this.setGatherNum(targetIndex)
				this.isSearch = false
			},
			close() {
				this.isNotice = false
			},
			//视频组件1(跳转上次观看)
			handleZujian1(){
				// this.isZujian1 = !this.isZujian1 
				if(this.preIndex){
					this.setGatherNum(this.preIndex)
					this.preIndex =0
				}
			},
			//视频组件2
			handleZujian2(){
				this.isZujian2 = !this.isZujian2
				
			},
			//倍速
			 bindSpeedChange(e) {
				// console.log('picker发送选择改变，携带值为', e.detail.value)
				this.SpeedIndex = e.detail.value
				if(this.SpeedIndex == 1){
					this.isZujian2 = false
				}else{
					this.isZujian2 = true
				}
				let a = this.SpeedArray[this.SpeedIndex].replace('倍速','')
				// console.log('this.SpeedArray[SpeedIndex])',a)
				this.videoContext.playbackRate(Number(a));
			},
			//视频组件3
			handleZujian3(){
				this.isZujian3 = !this.isZujian3 
			},
			//线路
			bindLineChange(e){
				this.LineIndex = e.detail.value

				if(this.SpeedIndex == 0){
					this.isZujian3 = false
				}else{
					this.isZujian3 = true
				}
				// this.$u.toast(`线路切换为${this.LineArray[this.LineIndex]}`)
			},
			handleZujian4(){
				this.isZujian4 = !this.isZujian4
				//在开启自动续播时，先判断是否已经播放完毕，等待续播
				if(this.currentTime == this.duration){
					this.HandleplayEnd()
				}
				// 保存自动续播状态到本地存储
				uni.setStorageSync('autoPlayNext', this.isZujian4)
				if (this.isZujian4) {
					this.$u.toast('已开启自动续播')
				} else {
					this.$u.toast('已关闭自动续播')
				}
			},
			//处理视频播放结束
			async HandleplayEnd(){
				// 如果开启了自动续播，则自动切换到下一集
				if (this.isZujian4) {
					// 检查是否有下一集
					const nextEpisodeIndex = this.EpisodeIndex + 1
					if (nextEpisodeIndex <= this.episodeTotal) {
						// 显示提示
						uni.showLoading({
							title: '正在为您自动切换下一集',
							mask: true
						})
						// 延迟一下再切换，让用户看到提示
						setTimeout(async () => {
							await this.setGatherNum(nextEpisodeIndex)
							uni.hideLoading()
							this.$u.toast(`已自动切换到第${nextEpisodeIndex}集`)
						}, 500)
					} else {
						// 已经是最后一集
						this.$u.toast('已经是最后一集了')
					}
				}
			},
			//官方预加载方法
			preloadplaylet() {
				const plugin = tt.requirePlugin('ttf57583c86a3aace011');
			    plugin.preloadResourceVideo({
			      albumId: this.openDramaId,
			      episodeId: this.openEpisodeId,
			      cloudType: 1,
			      version: 1,
			      success: () => {
			        tt.showToast({
			          title: '短剧预加载成功', // 内容
			        });
			        // this.setData({
			        //   playletshow: true,
			        // });
			      },
			      fail: (error) => {
			        console.log("短剧预加载失败", error);
			        tt.showToast({
			          icon: 'fail',
			          title: '短剧预加载失败'
			        })
			        // this.setData({
			        //   playletshow: true,
			        // });
			      },
			    });
			  },
		},
		computed: {
			chapterPageCount() {
				if (!this.episodeTotal) return 0
				return Math.ceil(this.episodeTotal / 30)
			},
			currentPageepisodeList() {
				const start = this.currentPageIndex * 30
				const end = start + 30
				return this.episodeList.slice(start, end)
			}
		}
	}
</script>

<style lang="less" scoped>
	@import url('./index.less');
</style>